package com.bodu.system.template.storage;

import cn.hutool.core.io.FileUtil;
import com.bodu.system.entity.po.FilePo;
import com.bodu.system.entity.po.StorageConfigPo;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author Administrator
 */
@Component
public class LocalTemplate implements FileTemplate{

    /**
     *
     * @param useConfig
     * @param file
     * @return
     */
    @Override
    @SneakyThrows
    public FilePo upload(StorageConfigPo useConfig, MultipartFile file) {
        String local = useConfig.getBucket();
        FilePo filePo = new FilePo();
        filePo.setStorageConfigId(useConfig.getId());
        String originalFileName = file.getOriginalFilename();
        filePo.setFileName(originalFileName);
        filePo.setFileType(file.getContentType());
        String ext = originalFileName.substring(originalFileName.lastIndexOf(".") +1);
        filePo.setCreateName(System.currentTimeMillis() + "." + ext);
        filePo.setFileSize(file.getSize());
        filePo.setFilePath(local + File.separator + filePo.getCreateName());
        filePo.setUrl(useConfig.getDomain()+ File.separator + filePo.getCreateName());
        FileUtil.writeFromStream(file.getInputStream(), filePo.getFilePath());
        return filePo;
    }

//    public void delete(String url) {
//        String key = url.replaceAll(fileProperties.getLocal().getNgxinxUrl() + CommonConstant.DIR_SPLIT, "");
//        File file = new File(fileProperties.getLocal().getUploadPath() + CommonConstant.DIR_SPLIT + key);
//        if (file.exists()) {
//            file.delete();
//        }
//    }
//
//    public void download(String url, HttpServletResponse response) {
//        FileUtil.downLoad(url, fileProperties.getLocal().getNgxinxUrl(), response);
//    }
}
